package com.coldfusiondocs.controller
{
    import com.coldfusiondocs.delegate.IDataDelegate;
    import com.coldfusiondocs.event.GetLinkEvent;
    import com.coldfusiondocs.factories.AppFactory;
    import com.coldfusiondocs.model.ApplicationModel;
    import com.coldfusiondocs.model.LinkModel;
    import com.coldfusiondocs.model.presentation.LinkPresentationModel;
    import com.coldfusiondocs.model.vo.ObjectVO;
    
    import mx.collections.ArrayCollection;
    import mx.collections.Sort;
    import mx.collections.SortField;
    import mx.rpc.events.ResultEvent;
    
    import org.swizframework.controller.AbstractController;
    import org.swizframework.utils.chain.*;

    public class MainController extends AbstractController
    {
        // PUBLIC PROPERTIES
        [Inject(source="dataDelegate")]
        public var delegate : IDataDelegate;
        
        [Inject(source="appModel")]
        public var appModel : ApplicationModel; 
        
        [Inject(source="linkModel")]
        public var linkModel : LinkModel;
        
 		[Inject(source="linkPresentationModel")]
		[Bindable]
		public var linkPresentationModel : LinkPresentationModel;        
        
        // CONSTRUCTOR
        
        public function MainController()
        {
            super();
        }
        
        // PUBLIC METHODS
        
        /**
         * Load the Initial Data.
         */ 
        [Mediate("mx.events.FlexEvent.APPLICATION_COMPLETE" )]
        public function loadXmlFiles() : void
        {
            this.appModel.currentState = ApplicationModel.STATE_LOADING;
            executeServiceCall( delegate.loadAdobeCFML(), adobeLoadHandler );
            executeServiceCall( delegate.loadRailoCFML(), railoLoadHandler );
        }
        
        [Mediate("TypeChangeEvent.TYPE_CHANGE" )]
        public function changeTabSelection() : void
        {
 			linkPresentationModel.isIframeVisible = false;
        }

        [Mediate("ItemClickEvent.ITEM_CLICK_ADOBE", properties="_item" )]
        public function loadItem(item:String) : void
        {
        	var sourceData:ArrayCollection;
			var prependURL:String;
			
			sourceData = appModel.all_adobe_cfml_tags;
			prependURL = "http://www.coldfusiondocs.com/htmldocs/load.cfm?object=";
			appModel.isProcessing = true;
			processClick(sourceData, prependURL, item);
        }
        
        [Mediate("ItemClickEvent.ITEM_CLICK_RAILO", properties="_item" )]
        public function loadRailoItem(item:String) : void
        {
        	var sourceData:ArrayCollection;
			var prependURL:String;
			
			sourceData = appModel.all_railo_cfml_tags;
			prependURL = "http://www.coldfusiondocs.com/railohtml/load.cfm?object=";
			appModel.isProcessing = true;
			processClick(sourceData, prependURL, item);
        }           
        // EVENT HANDLERS
        
        private function railoLoadHandler( event : ResultEvent ):void
        {
        	var xml:XML = event.result as XML;
			var _items:Array = AppFactory.buildArrayofObjectsFromXML(xml);
			
			//sort the data
			var _sortedItems:ArrayCollection = new ArrayCollection(_items);
			var sort:Sort = new Sort();
			sort.fields =[ new SortField("objectName", true, false)];
			_sortedItems.sort = sort;
			_sortedItems.refresh();
			
			//update the Model
			this.appModel.all_railo_cfml_tags = new ArrayCollection(_items);
        }
        
        private function adobeLoadHandler( event : ResultEvent ) : void
        {
			var xml:XML = event.result as XML;

			// parse the XML
			var _items:Array = AppFactory.buildArrayofObjectsFromXML(xml);
			
			//sort the data alphabetically
			var _sortedItems:ArrayCollection = new ArrayCollection(_items);
			var sort:Sort = new Sort();
			sort.fields =[ new SortField("objectName", true, false)];
			_sortedItems.sort = sort;
			_sortedItems.refresh();
			
			//update the Model
			this.appModel.all_adobe_cfml_tags = _sortedItems;

			// assign the list of categories 
			var _categories:Array = AppFactory.buildArrayofCategoriesfromXML(xml);
			this.appModel.all_adobe_cfml_categories = new ArrayCollection(_categories);
			
			// finally, change the state
			this.appModel.currentState = ApplicationModel.STATE_READY;
        }
        
       private function processClick(sourceData:ArrayCollection, prependURL:String, item:String):void
        {
			var selectedItem:ObjectVO ;

			// find the item from the model
			for each(var obj:ObjectVO in sourceData){
				if (obj.objectName == item){
					selectedItem = obj;
					break;
				}
			}	
			
			// get the docURL for the item
			var urlBreak:Array = selectedItem.docURL.toString().split("/");
			var fileName:Array = urlBreak[urlBreak.length-1].split("#");
			var frameSource:String = prependURL + fileName[0].toString();
			
			//update the Model
			if(linkPresentationModel.iframeURL.toString() != frameSource)
			{
				linkPresentationModel.iframeURL = frameSource;  
			}

			// make the iframe visible if its not already
			linkPresentationModel.isIframeVisible = true;
			
			// update the Model currentItem
			linkPresentationModel.currentItem = selectedItem.objectName.toString();
			
			// fire the GetLink Event so the 'useful urls' gets updated as well
			dispatcher.dispatchEvent(new GetLinkEvent(GetLinkEvent.GET_LINK, selectedItem.objectName.toString()));	
			
			appModel.isProcessing = false;							
        }        
        
    }
}